package com.his.common.util;

import org.apache.commons.collections4.CollectionUtils;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.Reader;
import java.sql.Clob;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * @Author xiaoxiaoping
 * @Date 2020/3/19 14:18
 * @Version 1.0
 */
public class Utils {
    /**
     *
     * @param list 所有元素的平级集合，map包含id和pid
     * @param pid 顶级节点的pid，可以为null
     * @param idName id位的名称，一般为id或者code
     * @return 树
     */
    public static List<Map<String, Object>> getTree(List<Map<String, Object>> list, String pid, String idName) {
        List<Map<String, Object>> res = new ArrayList<Map<String,Object>>();
        if (CollectionUtils.isNotEmpty(list))
            for (Map<String, Object> map : list) {
                if(pid == null && map.get("p"+idName) == null || map.get("p"+idName) != null && map.get("p"+idName).equals(pid)){
                    String id = (String) map.get(idName);
                    map.put("children", getTree(list, id, idName));
                    res.add(map);
                }
            }
        return res;
    }

    /**
     * clob2String
     * @param clob
     * @return
     * @throws SQLException
     * @throws IOException
     */
    public static String clob2String(Clob clob) throws SQLException, IOException
    {
        String reString = "";
        Reader is = clob.getCharacterStream();// 得到流
        BufferedReader br = new BufferedReader(is);
        String s = br.readLine();
        StringBuffer sb = new StringBuffer();
        while (s != null)
        {
            // 执行循环将字符串全部取出付值给StringBuffer由StringBuffer转成STRING
            sb.append(s);
            s = br.readLine();
        }
        reString = sb.toString();
        return reString;
    }

}
